//
//  Status.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/8/6.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit
import SDWebImage
class Status: NSObject {
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博neir
    var text: String?
    /// 微博来源
    var source: String?
    /// 配图
    var pic_urls: [[String: AnyObject]]? {
        didSet{
            if pic_urls!.count == 0 {
                return
            }
            
            storePictureURLs = [NSURL]()
            storeLargePictureURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storePictureURLs?.append(NSURL(string: urlString)!)
                    
                    let largeURLString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storeLargePictureURLs?.append(NSURL(string: largeURLString)!)
                }
            }
         }
    }
    /// 转发微博
    var retweeted_status: Status?

    private var storePictureURLs: [NSURL]?
    
    private var storeLargePictureURLs: [NSURL]?
    
    var pictureURLs: [NSURL]? {
        return retweeted_status == nil ? storePictureURLs : retweeted_status!.storePictureURLs
    }
    var largePictureURLs: [NSURL]? {
        return retweeted_status == nil ? storeLargePictureURLs : retweeted_status?.storeLargePictureURLs
    }

    /// 显示微博所需行高
    var rowHeight: CGFloat?
    /// 用户
    var user: User?
    class func loadstatus(finished:(dataList: [Status]?,error: NSError?)->()) {
        NetworkTools.sharedNetworkTools.loadStatus { (result, error) -> () in
            if error != nil {
                finished(dataList: nil, error: error)
                return
            }
            if let array = result!["statuses"] as? [[String: AnyObject]] {
                
                var list = [Status]()
                for dict in array {
                    list.append(Status(dict: dict))
                }
                //调用缓存图片函数
                self.cacheWebImage(list, finished: finished)
                
                finished(dataList: list, error: nil)
            } else {
                finished(dataList: nil, error: nil)
            }
        }
    }
    
    private class func cacheWebImage(list: [Status],finished:(dataList: [Status]?,error: NSError?)->()) {
        
        let group = dispatch_group_create()
        
        for status in list {
            
            guard let urls = status.pictureURLs else {
                continue
            }
            
            for imageUrl in urls {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(dataList: list, error: nil)
        }
    }
    
    //构造函数
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    
    }
    override func setValue(value: AnyObject?, forKey key: String){
        super.setValue(value, forKey: key)
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                user = User(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = Status(dict:dict)
            }
            return
        }
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override var description: String {
        let keys = ["created_at","id","text","source","pic_urls",]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}
